# Load Packages -----------------------------------------------------------
library(lavaan)

# Load Data ---------------------------------------------------------------
# Set file path
setwd("")

load("drop_in_ocean_data.rdata")


# CFA ---------------------------------------------------------------------
# Fit statistics of interest
FIT <- c("chisq.scaled","df", "cfi.scaled", "srmr", "rmsea.scaled", "rmsea.ci.lower.scaled", "rmsea.ci.upper.scaled")

# Define variables of interest
vars <- c("felon_benefits", "felon_voting", "cit_osight", "pub_defend", 
          "blm_support", "p.race.fair", "p.exces.force", "p.account", "court.fair.all")

# Define model
one_dim <- '
# Defining Latent Variables
cjs_atts =~ NA*felon_benefits + felon_voting + cit_osight + pub_defend + blm_support + p.race.fair + p.exces.force + p.account + court.fair.all

# Defining Metric
cjs_atts ~~ 1*cjs_atts

# Error covariances based on common content
felon_voting ~~ felon_benefits
cit_osight ~~ pub_defend + blm_support
p.race.fair ~~ p.exces.force + p.account
p.exces.force ~~ p.account
pub_defend ~~ blm_support
'
# Estimate model
dv_cfa <- cfa(one_dim, cjs.df, mimic = "Mplus", ordered = vars)
summary(dv_cfa, standardized = T)
# look at fit
round(fitMeasures(dv_cfa)[FIT], 3)


# ** CFAs by Group --------------------------------------------------------
# Estimate loadings freely
dv_cfa_bw <- cfa(one_dim, cjs.df, mimic = "Mplus", ordered = vars, group = "black",
                 group.equal = "none")
summary(dv_cfa_bw, standardized = T)
round(fitMeasures(dv_cfa_bw)[FIT], 3)

# Constrain loadings across grops
dv_cfa_bw_metric <- cfa(one_dim, cjs.df, mimic = "Mplus", ordered = vars, group = "black",
                 group.equal = c("loadings"))
summary(dv_cfa_bw_metric, standardized = T)
round(fitMeasures(dv_cfa_bw_metric)[FIT], 3)


